<template>
  <div class="min-h-screen py-8 px-4 sm:px-6 lg:px-8">
    <div class="max-w-7xl mx-auto">
      <!-- 页面标题 -->
      <div class="text-center mb-12">
        <h1 class="text-4xl font-bold mb-4 tech-text">WebRTC API</h1>
        <p class="text-gray-300 text-lg">
          实时音视频通信、数据传输和点对点连接
        </p>
      </div>

      <!-- 浏览器支持提示 -->
      <div v-if="!isSupported" class="tech-card mb-8 border-yellow-600">
        <div class="flex items-center mb-4">
          <i class="i-carbon-warning text-yellow-500 text-xl mr-3"></i>
          <h3 class="text-xl font-semibold text-yellow-500">浏览器支持提示</h3>
        </div>
        <p class="text-gray-300">
          您的浏览器不支持 WebRTC API。此功能需要现代浏览器支持。
        </p>
      </div>

      <template v-if="isSupported">
        <!-- 本地媒体流 -->
        <div class="tech-card mb-8">
          <div class="flex items-center mb-6">
            <i class="i-carbon-video text-3xl text-tech-accent mr-3"></i>
            <h2 class="text-2xl font-semibold text-white">本地媒体流</h2>
          </div>

          <div class="space-y-6">
            <!-- 媒体控制 -->
            <div class="bg-gray-800 rounded-lg p-6">
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
                <button
                  @click="startLocalVideo"
                  :disabled="isLocalVideoActive"
                  class="tech-button disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <i class="i-carbon-video mr-2"></i>
                  {{ isLocalVideoActive ? '视频已开启' : '开启摄像头' }}
                </button>

                <button
                  @click="startLocalAudio"
                  :disabled="isLocalAudioActive"
                  class="bg-purple-600 hover:bg-purple-700 text-white px-6 py-3 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <i class="i-carbon-microphone mr-2"></i>
                  {{ isLocalAudioActive ? '音频已开启' : '开启麦克风' }}
                </button>

                <button
                  @click="startScreenShare"
                  :disabled="isScreenSharing"
                  class="bg-green-600 hover:bg-green-700 text-white px-6 py-3 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <i class="i-carbon-screen mr-2"></i>
                  {{ isScreenSharing ? '共享中...' : '屏幕共享' }}
                </button>

                <button
                  @click="stopAllMedia"
                  :disabled="!isLocalVideoActive && !isLocalAudioActive && !isScreenSharing"
                  class="bg-red-600 hover:bg-red-700 text-white px-6 py-3 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <i class="i-carbon-stop-filled mr-2"></i>
                  停止所有媒体
                </button>
              </div>

              <!-- 本地视频预览 -->
              <div class="bg-black rounded-lg overflow-hidden">
                <video
                  ref="localVideoElement"
                  autoplay
                  muted
                  playsinline
                  class="w-full h-auto"
                ></video>
              </div>
            </div>

            <!-- 媒体设备列表 -->
            <div class="bg-gray-800 rounded-lg p-6">
              <h3 class="text-white font-semibold mb-4">可用媒体设备</h3>

              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <!-- 音频输入 -->
                <div>
                  <label class="block text-gray-300 mb-2">音频输入设备:</label>
                  <select
                    v-model="selectedAudioInput"
                    class="w-full bg-gray-700 text-white border border-gray-600 rounded-lg px-3 py-2 focus:border-tech-accent outline-none"
                  >
                    <option value="">默认</option>
                    <option
                      v-for="device in audioInputDevices"
                      :key="device.deviceId"
                      :value="device.deviceId"
                    >
                      {{ device.label || `设备 ${device.deviceId.slice(0, 8)}` }}
                    </option>
                  </select>
                </div>

                <!-- 视频输入 -->
                <div>
                  <label class="block text-gray-300 mb-2">视频输入设备:</label>
                  <select
                    v-model="selectedVideoInput"
                    class="w-full bg-gray-700 text-white border border-gray-600 rounded-lg px-3 py-2 focus:border-tech-accent outline-none"
                  >
                    <option value="">默认</option>
                    <option
                      v-for="device in videoInputDevices"
                      :key="device.deviceId"
                      :value="device.deviceId"
                    >
                      {{ device.label || `设备 ${device.deviceId.slice(0, 8)}` }}
                    </option>
                  </select>
                </div>
              </div>

              <button
                @click="enumerateDevices"
                class="mt-4 bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg transition-colors text-sm"
              >
                <i class="i-carbon-renew mr-1"></i>
                刷新设备列表
              </button>
            </div>
          </div>
        </div>

        <!-- 点对点连接 -->
        <div class="tech-card mb-8">
          <div class="flex items-center mb-6">
            <i class="i-carbon-network-3 text-3xl text-tech-accent mr-3"></i>
            <h2 class="text-2xl font-semibold text-white">点对点连接（本地模拟）</h2>
          </div>

          <div class="space-y-6">
            <!-- 连接控制 -->
            <div class="bg-gray-800 rounded-lg p-6">
              <div class="flex gap-3 mb-6">
                <button
                  @click="createConnection"
                  :disabled="isConnected || !localStream"
                  class="tech-button flex-1 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <i class="i-carbon-connection-signal mr-2"></i>
                  {{ isConnected ? '已连接' : '创建连接' }}
                </button>

                <button
                  @click="closeConnection"
                  :disabled="!isConnected"
                  class="bg-red-600 hover:bg-red-700 text-white px-6 py-3 rounded-lg transition-colors flex-1 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <i class="i-carbon-close mr-2"></i>
                  关闭连接
                </button>
              </div>

              <!-- 连接状态 -->
              <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div class="bg-gray-900 rounded-lg p-4 text-center">
                  <div class="text-gray-400 text-sm mb-1">连接状态</div>
                  <div
                    :class="[
                      connectionState === 'connected' ? 'text-green-400' :
                      connectionState === 'connecting' ? 'text-yellow-400' :
                      connectionState === 'disconnected' ? 'text-red-400' :
                      'text-gray-400'
                    ]"
                    class="text-lg font-semibold"
                  >
                    {{ getConnectionStateText(connectionState) }}
                  </div>
                </div>

                <div class="bg-gray-900 rounded-lg p-4 text-center">
                  <div class="text-gray-400 text-sm mb-1">ICE 状态</div>
                  <div class="text-lg font-semibold text-white">
                    {{ iceConnectionState }}
                  </div>
                </div>

                <div class="bg-gray-900 rounded-lg p-4 text-center">
                  <div class="text-gray-400 text-sm mb-1">信令状态</div>
                  <div class="text-lg font-semibold text-white">
                    {{ signalingState }}
                  </div>
                </div>
              </div>
            </div>

            <!-- 远程视频 -->
            <div class="bg-gray-800 rounded-lg p-6">
              <h3 class="text-white font-semibold mb-4">远程视频流</h3>
              <div class="bg-black rounded-lg overflow-hidden">
                <video
                  ref="remoteVideoElement"
                  autoplay
                  playsinline
                  class="w-full h-auto"
                ></video>
              </div>
            </div>
          </div>
        </div>

        <!-- 数据通道 -->
        <div class="tech-card mb-8">
          <div class="flex items-center mb-6">
            <i class="i-carbon-data-base text-3xl text-tech-accent mr-3"></i>
            <h2 class="text-2xl font-semibold text-white">数据通道（DataChannel）</h2>
          </div>

          <div class="space-y-6">
            <!-- 数据通道控制 -->
            <div class="bg-gray-800 rounded-lg p-6">
              <div class="flex gap-3 mb-4">
                <button
                  @click="createDataChannel"
                  :disabled="!isConnected || dataChannel !== null"
                  class="tech-button disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <i class="i-carbon-add mr-2"></i>
                  {{ dataChannel ? '数据通道已创建' : '创建数据通道' }}
                </button>

                <button
                  @click="closeDataChannel"
                  :disabled="!dataChannel"
                  class="bg-red-600 hover:bg-red-700 text-white px-6 py-3 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <i class="i-carbon-close mr-2"></i>
                  关闭通道
                </button>
              </div>

              <div class="bg-gray-900 rounded-lg p-4">
                <div class="text-gray-400 text-sm mb-1">通道状态</div>
                <div
                  :class="[
                    dataChannelState === 'open' ? 'text-green-400' :
                    dataChannelState === 'connecting' ? 'text-yellow-400' :
                    'text-gray-400'
                  ]"
                  class="text-lg font-semibold"
                >
                  {{ dataChannelState || '未创建' }}
                </div>
              </div>
            </div>

            <!-- 消息发送 -->
            <div class="bg-gray-800 rounded-lg p-6">
              <h3 class="text-white font-semibold mb-4">发送消息</h3>

              <div class="flex gap-3 mb-4">
                <input
                  v-model="messageToSend"
                  type="text"
                  placeholder="输入要发送的消息..."
                  @keyup.enter="sendMessage"
                  class="flex-1 bg-gray-700 text-white border border-gray-600 rounded-lg px-4 py-3 focus:border-tech-accent outline-none"
                >
                <button
                  @click="sendMessage"
                  :disabled="!dataChannel || dataChannelState !== 'open' || !messageToSend"
                  class="tech-button disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <i class="i-carbon-send mr-2"></i>
                  发送
                </button>
              </div>

              <div class="flex gap-3">
                <button
                  @click="sendFile"
                  :disabled="!dataChannel || dataChannelState !== 'open'"
                  class="bg-purple-600 hover:bg-purple-700 text-white px-4 py-2 rounded-lg transition-colors text-sm disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <i class="i-carbon-document mr-1"></i>
                  发送文件
                </button>

                <button
                  @click="sendBinaryData"
                  :disabled="!dataChannel || dataChannelState !== 'open'"
                  class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg transition-colors text-sm disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <i class="i-carbon-code mr-1"></i>
                  发送二进制数据
                </button>
              </div>
            </div>

            <!-- 消息历史 -->
            <div v-if="messages.length > 0" class="bg-gray-800 rounded-lg p-6">
              <div class="flex items-center justify-between mb-4">
                <h3 class="text-white font-semibold">消息历史</h3>
                <button
                  @click="clearMessages"
                  class="text-red-400 hover:text-red-300 text-sm"
                >
                  <i class="i-carbon-clean mr-1"></i>
                  清空
                </button>
              </div>

              <div class="space-y-2 max-h-64 overflow-y-auto">
                <div
                  v-for="(msg, index) in messages"
                  :key="index"
                  :class="[
                    msg.type === 'sent' ? 'bg-blue-900/30' : 'bg-gray-900',
                    'rounded-lg p-3'
                  ]"
                >
                  <div class="flex justify-between items-start mb-1">
                    <span
                      :class="[
                        msg.type === 'sent' ? 'text-blue-400' : 'text-green-400'
                      ]"
                      class="font-semibold text-sm"
                    >
                      {{ msg.type === 'sent' ? '发送' : '接收' }}
                    </span>
                    <span class="text-gray-400 text-xs">{{ msg.timestamp }}</span>
                  </div>
                  <p class="text-white break-words">{{ msg.content }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 连接统计 -->
        <div v-if="isConnected" class="tech-card mb-8">
          <h2 class="text-2xl font-semibold mb-6 text-white">连接统计</h2>

          <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div class="bg-gray-800 rounded-lg p-6 text-center">
              <div class="text-3xl font-bold text-blue-400">{{ stats.bytesSent }}</div>
              <div class="text-gray-400 text-sm mt-1">发送字节</div>
            </div>

            <div class="bg-gray-800 rounded-lg p-6 text-center">
              <div class="text-3xl font-bold text-green-400">{{ stats.bytesReceived }}</div>
              <div class="text-gray-400 text-sm mt-1">接收字节</div>
            </div>

            <div class="bg-gray-800 rounded-lg p-6 text-center">
              <div class="text-3xl font-bold text-purple-400">{{ stats.packetsSent }}</div>
              <div class="text-gray-400 text-sm mt-1">发送包数</div>
            </div>

            <div class="bg-gray-800 rounded-lg p-6 text-center">
              <div class="text-3xl font-bold text-yellow-400">{{ stats.packetsReceived }}</div>
              <div class="text-gray-400 text-sm mt-1">接收包数</div>
            </div>
          </div>

          <button
            @click="updateStats"
            class="mt-4 tech-button"
          >
            <i class="i-carbon-renew mr-2"></i>
            刷新统计
          </button>
        </div>
      </template>

      <!-- API 信息 -->
      <div class="tech-card">
        <h3 class="text-xl font-semibold mb-4 text-white">API 信息</h3>
        <div class="space-y-4 text-gray-300">
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">浏览器支持</h4>
            <p>Chrome 23+, Firefox 22+, Safari 11+, Edge 79+</p>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">核心 API</h4>
            <ul class="list-disc list-inside space-y-1">
              <li><code class="bg-gray-800 px-2 py-1 rounded">RTCPeerConnection</code> - 点对点连接</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">RTCDataChannel</code> - 数据通道</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">getUserMedia()</code> - 获取媒体流</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">getDisplayMedia()</code> - 屏幕共享</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">enumerateDevices()</code> - 枚举设备</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">基本用法</h4>
            <pre class="bg-gray-800 p-4 rounded text-sm overflow-x-auto">
<span class="text-gray-500">// 创建 PeerConnection</span>
<span class="text-blue-400">const</span> pc = <span class="text-blue-400">new</span> RTCPeerConnection({
  iceServers: [{ urls: <span class="text-green-400">'stun:stun.l.google.com:19302'</span> }]
});

<span class="text-gray-500">// 添加媒体流</span>
<span class="text-blue-400">const</span> stream = <span class="text-blue-400">await</span> navigator.mediaDevices.getUserMedia({
  video: <span class="text-blue-400">true</span>,
  audio: <span class="text-blue-400">true</span>
});
stream.getTracks().forEach(track => pc.addTrack(track, stream));

<span class="text-gray-500">// 创建数据通道</span>
<span class="text-blue-400">const</span> dataChannel = pc.createDataChannel(<span class="text-green-400">'chat'</span>);
dataChannel.onmessage = (event) => {
  console.log(<span class="text-green-400">'收到消息:'</span>, event.data);
};</pre>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">使用场景</h4>
            <ul class="list-disc list-inside space-y-1 text-sm">
              <li>视频会议和在线会议</li>
              <li>实时音视频通话</li>
              <li>屏幕共享和远程协作</li>
              <li>点对点文件传输</li>
              <li>在线游戏和实时互动</li>
              <li>远程教育和培训</li>
              <li>IoT 设备通信</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">优势特性</h4>
            <ul class="list-disc list-inside space-y-1 text-sm">
              <li><strong>低延迟：</strong>点对点通信，延迟极低</li>
              <li><strong>无需插件：</strong>原生浏览器支持</li>
              <li><strong>安全加密：</strong>内置 DTLS 和 SRTP 加密</li>
              <li><strong>NAT 穿透：</strong>自动处理 NAT 和防火墙</li>
              <li><strong>自适应：</strong>根据网络状况调整质量</li>
              <li><strong>多媒体支持：</strong>音频、视频、数据传输</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">信令过程</h4>
            <div class="text-sm space-y-2">
              <p>1. <strong>创建 Offer：</strong>呼叫方创建 SDP offer</p>
              <p>2. <strong>交换 SDP：</strong>通过信令服务器交换 SDP</p>
              <p>3. <strong>创建 Answer：</strong>接收方创建 SDP answer</p>
              <p>4. <strong>ICE 候选：</strong>交换 ICE 候选地址</p>
              <p>5. <strong>建立连接：</strong>完成 NAT 穿透，建立连接</p>
            </div>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">最佳实践</h4>
            <ul class="list-disc list-inside space-y-1 text-sm">
              <li>使用 STUN/TURN 服务器确保连接成功</li>
              <li>处理网络切换和重连情况</li>
              <li>监控连接质量和带宽</li>
              <li>实现完善的错误处理机制</li>
              <li>考虑移动设备的特殊情况</li>
              <li>提供降级方案（如录制）</li>
              <li>注意隐私和权限管理</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">常见问题</h4>
            <div class="text-sm space-y-2">
              <p><strong>Q: 为什么需要信令服务器？</strong></p>
              <p>A: WebRTC 只负责媒体传输，需要信令服务器交换连接信息（SDP、ICE）</p>
              <p class="mt-2"><strong>Q: STUN 和 TURN 的区别？</strong></p>
              <p>A: STUN 用于发现公网地址，TURN 用于中继流量（当 P2P 失败时）</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'

// 类型定义
interface Message {
  type: 'sent' | 'received'
  content: string
  timestamp: string
}

interface Stats {
  bytesSent: number
  bytesReceived: number
  packetsSent: number
  packetsReceived: number
}

// 响应式状态
const isSupported = ref(false)

// 本地媒体流
const localVideoElement = ref<HTMLVideoElement | null>(null)
const isLocalVideoActive = ref(false)
const isLocalAudioActive = ref(false)
const isScreenSharing = ref(false)
const localStream = ref<MediaStream | null>(null)

// 媒体设备
const audioInputDevices = ref<MediaDeviceInfo[]>([])
const videoInputDevices = ref<MediaDeviceInfo[]>([])
const selectedAudioInput = ref('')
const selectedVideoInput = ref('')

// 点对点连接
const remoteVideoElement = ref<HTMLVideoElement | null>(null)
const isConnected = ref(false)
const connectionState = ref<RTCPeerConnectionState>('new')
const iceConnectionState = ref('')
const signalingState = ref('')

let peerConnection1: RTCPeerConnection | null = null
let peerConnection2: RTCPeerConnection | null = null

// 数据通道
const dataChannel = ref<RTCDataChannel | null>(null)
const dataChannelState = ref('')
const messageToSend = ref('')
const messages = ref<Message[]>([])

// 统计
const stats = ref<Stats>({
  bytesSent: 0,
  bytesReceived: 0,
  packetsSent: 0,
  packetsReceived: 0
})

let statsInterval: ReturnType<typeof setInterval> | null = null

// 初始化
onMounted(() => {
  isSupported.value = !!(
    navigator.mediaDevices &&
    navigator.mediaDevices.getUserMedia &&
    window.RTCPeerConnection
  )
  
  if (isSupported.value) {
    enumerateDevices()
  }
})

// 清理
onUnmounted(() => {
  stopAllMedia()
  closeConnection()
  
  if (statsInterval) {
    clearInterval(statsInterval)
  }
})

// 枚举设备
const enumerateDevices = async () => {
  try {
    const devices = await navigator.mediaDevices.enumerateDevices()
    
    audioInputDevices.value = devices.filter(d => d.kind === 'audioinput')
    videoInputDevices.value = devices.filter(d => d.kind === 'videoinput')
  } catch (error) {
    console.error('枚举设备失败:', error)
  }
}

// 开启摄像头
const startLocalVideo = async () => {
  try {
    const constraints: MediaStreamConstraints = {
      video: selectedVideoInput.value 
        ? { deviceId: { exact: selectedVideoInput.value } }
        : true,
      audio: false
    }
    
    const stream = await navigator.mediaDevices.getUserMedia(constraints)
    
    if (localVideoElement.value) {
      localVideoElement.value.srcObject = stream
    }
    
    if (localStream.value) {
      stream.getTracks().forEach(track => {
        localStream.value?.addTrack(track)
      })
    } else {
      localStream.value = stream
    }
    
    isLocalVideoActive.value = true
  } catch (error) {
    console.error('无法访问摄像头:', error)
    alert('无法访问摄像头，请检查权限设置')
  }
}

// 开启麦克风
const startLocalAudio = async () => {
  try {
    const constraints: MediaStreamConstraints = {
      video: false,
      audio: selectedAudioInput.value
        ? { deviceId: { exact: selectedAudioInput.value } }
        : true
    }
    
    const stream = await navigator.mediaDevices.getUserMedia(constraints)
    
    if (localStream.value) {
      stream.getTracks().forEach(track => {
        localStream.value?.addTrack(track)
      })
    } else {
      localStream.value = stream
    }
    
    isLocalAudioActive.value = true
  } catch (error) {
    console.error('无法访问麦克风:', error)
    alert('无法访问麦克风，请检查权限设置')
  }
}

// 屏幕共享
const startScreenShare = async () => {
  try {
    const stream = await navigator.mediaDevices.getDisplayMedia({
      video: true,
      audio: false
    })
    
    if (localVideoElement.value) {
      localVideoElement.value.srcObject = stream
    }
    
    localStream.value = stream
    isScreenSharing.value = true
    
    // 监听停止共享
    stream.getVideoTracks()[0].onended = () => {
      isScreenSharing.value = false
    }
  } catch (error) {
    console.error('无法共享屏幕:', error)
  }
}

// 停止所有媒体
const stopAllMedia = () => {
  if (localStream.value) {
    localStream.value.getTracks().forEach(track => track.stop())
    localStream.value = null
  }
  
  if (localVideoElement.value) {
    localVideoElement.value.srcObject = null
  }
  
  isLocalVideoActive.value = false
  isLocalAudioActive.value = false
  isScreenSharing.value = false
}

// 创建连接
const createConnection = async () => {
  if (!localStream.value) {
    alert('请先开启摄像头或麦克风')
    return
  }

  const configuration = {
    iceServers: [
      { urls: 'stun:stun.l.google.com:19302' },
      { urls: 'stun:stun1.l.google.com:19302' }
    ]
  }

  // 创建两个 PeerConnection 模拟点对点连接
  peerConnection1 = new RTCPeerConnection(configuration)
  peerConnection2 = new RTCPeerConnection(configuration)

  // PC1 -> PC2 的 ICE 候选
  peerConnection1.onicecandidate = (event) => {
    if (event.candidate) {
      peerConnection2?.addIceCandidate(event.candidate)
    }
  }

  // PC2 -> PC1 的 ICE 候选
  peerConnection2.onicecandidate = (event) => {
    if (event.candidate) {
      peerConnection1?.addIceCandidate(event.candidate)
    }
  }

  // 监听连接状态
  peerConnection1.onconnectionstatechange = () => {
    connectionState.value = peerConnection1?.connectionState || 'new'
  }

  peerConnection1.oniceconnectionstatechange = () => {
    iceConnectionState.value = peerConnection1?.iceConnectionState || ''
  }

  peerConnection1.onsignalingstatechange = () => {
    signalingState.value = peerConnection1?.signalingState || ''
  }

  // 接收远程流
  peerConnection2.ontrack = (event) => {
    if (remoteVideoElement.value) {
      remoteVideoElement.value.srcObject = event.streams[0]
    }
  }

  // 添加本地流
  localStream.value.getTracks().forEach(track => {
    peerConnection1?.addTrack(track, localStream.value!)
  })

  // 创建 offer
  const offer = await peerConnection1.createOffer()
  await peerConnection1.setLocalDescription(offer)
  await peerConnection2.setRemoteDescription(offer)

  // 创建 answer
  const answer = await peerConnection2.createAnswer()
  await peerConnection2.setLocalDescription(answer)
  await peerConnection1.setRemoteDescription(answer)

  isConnected.value = true

  // 开始统计
  startStatsMonitoring()
}

// 关闭连接
const closeConnection = () => {
  if (peerConnection1) {
    peerConnection1.close()
    peerConnection1 = null
  }
  
  if (peerConnection2) {
    peerConnection2.close()
    peerConnection2 = null
  }
  
  if (remoteVideoElement.value) {
    remoteVideoElement.value.srcObject = null
  }
  
  isConnected.value = false
  connectionState.value = 'closed'
  
  if (statsInterval) {
    clearInterval(statsInterval)
  }
}

// 创建数据通道
const createDataChannel = () => {
  if (!peerConnection1) return

  dataChannel.value = peerConnection1.createDataChannel('chat', {
    ordered: true
  })

  dataChannel.value.onopen = () => {
    dataChannelState.value = 'open'
  }

  dataChannel.value.onclose = () => {
    dataChannelState.value = 'closed'
  }

  dataChannel.value.onmessage = (event) => {
    messages.value.push({
      type: 'received',
      content: event.data,
      timestamp: new Date().toLocaleTimeString('zh-CN')
    })
  }

  // PC2 监听数据通道
  peerConnection2!.ondatachannel = (event) => {
    const channel = event.channel
    
    channel.onmessage = (e) => {
      // 回显消息（模拟接收）
      if (dataChannel.value && dataChannel.value.readyState === 'open') {
        dataChannel.value.send(e.data)
      }
    }
  }
}

// 关闭数据通道
const closeDataChannel = () => {
  if (dataChannel.value) {
    dataChannel.value.close()
    dataChannel.value = null
    dataChannelState.value = ''
  }
}

// 发送消息
const sendMessage = () => {
  if (!dataChannel.value || !messageToSend.value) return

  try {
    dataChannel.value.send(messageToSend.value)
    
    messages.value.push({
      type: 'sent',
      content: messageToSend.value,
      timestamp: new Date().toLocaleTimeString('zh-CN')
    })
    
    messageToSend.value = ''
  } catch (error) {
    console.error('发送消息失败:', error)
  }
}

// 发送文件
const sendFile = () => {
  const input = document.createElement('input')
  input.type = 'file'
  
  input.onchange = (e) => {
    const file = (e.target as HTMLInputElement).files?.[0]
    if (file && dataChannel.value) {
      const reader = new FileReader()
      reader.onload = () => {
        try {
          dataChannel.value?.send(`[文件] ${file.name} (${file.size} bytes)`)
          messages.value.push({
            type: 'sent',
            content: `发送文件: ${file.name}`,
            timestamp: new Date().toLocaleTimeString('zh-CN')
          })
        } catch (error) {
          console.error('发送文件失败:', error)
        }
      }
      reader.readAsArrayBuffer(file)
    }
  }
  
  input.click()
}

// 发送二进制数据
const sendBinaryData = () => {
  if (!dataChannel.value) return

  const data = new Uint8Array([1, 2, 3, 4, 5])
  
  try {
    dataChannel.value.send(data.buffer)
    
    messages.value.push({
      type: 'sent',
      content: `发送二进制数据: [${Array.from(data).join(', ')}]`,
      timestamp: new Date().toLocaleTimeString('zh-CN')
    })
  } catch (error) {
    console.error('发送二进制数据失败:', error)
  }
}

// 清空消息
const clearMessages = () => {
  messages.value = []
}

// 开始统计监控
const startStatsMonitoring = () => {
  statsInterval = setInterval(() => {
    updateStats()
  }, 1000)
}

// 更新统计
const updateStats = async () => {
  if (!peerConnection1) return

  try {
    const statsReport = await peerConnection1.getStats()
    
    statsReport.forEach((report) => {
      if (report.type === 'outbound-rtp') {
        stats.value.bytesSent = report.bytesSent || 0
        stats.value.packetsSent = report.packetsSent || 0
      }
      
      if (report.type === 'inbound-rtp') {
        stats.value.bytesReceived = report.bytesReceived || 0
        stats.value.packetsReceived = report.packetsReceived || 0
      }
    })
  } catch (error) {
    console.error('获取统计失败:', error)
  }
}

// 获取连接状态文本
const getConnectionStateText = (state: string): string => {
  const stateMap: Record<string, string> = {
    'new': '新建',
    'connecting': '连接中',
    'connected': '已连接',
    'disconnected': '已断开',
    'failed': '失败',
    'closed': '已关闭'
  }
  return stateMap[state] || state
}
</script>

<style scoped>
video {
  max-height: 400px;
  object-fit: contain;
  background: #000;
}
</style>

